﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using Bussiness_Objects;
using DataObjects.ADO;

namespace WindowsFormsApplication1
{
    /// <summary>
    /// form input thong tin chi thiet phieu nhap sach
    /// </summary>
    public partial class NhapSach : DevComponents.DotNetBar.Controls.SlidePanel
    {
        /// <summary>
        /// Danh sach bien
        /// </summary>
        #region Bien
        TheLoai _theLoai = new TheLoai();
        DataTable _tableTheLoai = new DataTable();
        SqlTheLoai _sqlTheLoai = new SqlTheLoai();

        TacGia _tacGia = new TacGia();
        DataTable _tableTacGia = new DataTable();
        SqlTacGia _sqlTacGia = new SqlTacGia();

        CTTacGia _ctTacGia = new CTTacGia();
        SqlCTTacGia _sqlCTTacGia = new SqlCTTacGia();

        DauSach _dauSach = new DauSach();
        SqlDauSach _sqlDauSach = new SqlDauSach();
        DataTable _tableDauSach = new DataTable();

        Sach _sach = new Sach();
        SqlSach _sqlSach = new SqlSach();
        DataTable _tableSach = new DataTable();

        CuonSach _cuonSach = new CuonSach();
        SqlCuonSach _sqlCuonSach = new SqlCuonSach();

        PhieuNhapSach _phieuNS = new PhieuNhapSach();
        SqlPhieuNhapSach _sqlPhieuNS = new SqlPhieuNhapSach();

        CTPhieuNhapSach _ctPNS = new CTPhieuNhapSach();
        SqlCTPhieuNhapSach _sqlCTPNS = new SqlCTPhieuNhapSach();

        TableDetail _detail;
#endregion

        /// <summary>
        /// Ham khoi tao, xay dung cau truc Form
        /// </summary>
        #region Khoi tao
        public NhapSach()
        {
            InitializeComponent();
            this.SlideOutButtonVisible = false;

            _detail = new TableDetail();
            _detail.SlideOutButtonVisible = false;
            _detail.dateTime.Value = dtimeNgayLap.Value;
            _detail.SlideSide = DevComponents.DotNetBar.Controls.eSlideSide.Left;
            this.Controls.Add(_detail);
            _detail.BringToFront();
            _detail.IsOpen = false;
            _detail.butNhap.Click += new EventHandler(butNhap_Click);

            dtimeNgayLap.Value = DateTime.Today;

            _detail.dateTime.ValueChanged += new EventHandler(dateTime_ValueChanged);            

            UpdateTheLoaiSach();
            UpdateTacGia();
            UpdateTenSach();
            UpdateNhaXB();            
        }       

        private void UpdateTheLoaiSach()
        {         
            _tableTheLoai = _sqlTheLoai.GetTable();

            cmbTheLoai.DataSource = _tableTheLoai;
            cmbTheLoai.DisplayMember = _tableTheLoai.Columns[1].ToString();
            cmbTheLoai.ValueMember = _tableTheLoai.Columns[0].ToString();          
        }

        private void UpdateTacGia()
        {            
            _tableTacGia = _sqlTacGia.GetTable();

            cmbTacGia_NhapSach.DataSource = _tableTacGia;
            cmbTacGia_NhapSach.DisplayMember = _tableTacGia.Columns[1].ToString();
            cmbTacGia_NhapSach.ValueMember = _tableTacGia.Columns[0].ToString();                     
        }

        private void UpdateTenSach()
        {
            _tableDauSach = _sqlDauSach.GetTable();

            cmbTenSach.DataSource = _tableDauSach;
            cmbTenSach.DisplayMember = _tableDauSach.Columns[1].ToString();
        }

        private void UpdateNhaXB()
        {
            _tableSach = _sqlSach.GetTable();

            cmbNhaXB.DataSource = _tableSach;
            cmbNhaXB.DisplayMember = _tableSach.Columns["NhaXuatBan"].ToString();
        }

        public void ShowSlide()
        {   
            this.IsOpen = true;
            _detail.ResetField();
            ResetField();
            UpdateSize();
        }

        public void UpdateSize()
        {
            this.Size = ((DevComponents.DotNetBar.Metro.MetroForm)MainForm._mainForm).Size;
            grbThongTin.Location = new Point(
                this.Size.Width / 2 - grbThongTin.Size.Width / 2,
                this.Size.Height / 2 - grbThongTin.Size.Height / 2);
            _detail.UpdateSize();
        }

        private void ResetField()
        {
            cmbTenSach.Text = null;
            cmbNhaXB.Text = null;
            dtimeNamXB.Text = null;
            txtGiaTien.Text = "0";
            txtSoLuong.Text = "0";
            txtTongTien.Text = null;
            txtTenTLS_ThemTLS.Text = null;
            txtTacGia_ThemTG.Text = null;
            dtimeNgaySinh_ThemTG.Text = null;
            panel_Result.Text = "";           

            cmbTenSach.Focus();
        }
        #endregion

        /// <summary>
        /// Thao tac du lieu
        /// </summary>
        #region Nhap lieu
        /// <summary>
        /// Nhap du lieu Tac Gia
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void butNhapTGia_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(txtTacGia_ThemTG.Text))
            {
                _tacGia.Ten = txtTacGia_ThemTG.Text;
                _tacGia.NgaySinh = dtimeNgaySinh_ThemTG.Text;
                string result = _sqlTacGia.Insert(_tacGia);
                if (result == "Success")
                {
                    panel_Result.Text = "Đã nhập tác giả thành công";
                    UpdateTacGia();
                }
                else
                    panel_Result.Text = result;
            }
            else
                panel_Result.Text = "Vui lòng nhập tên tác giả";
            
        }

        /// <summary>
        /// Nhap du lieu TheLoai
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void butNhapTLS_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(txtTenTLS_ThemTLS.Text))
            {
                _theLoai.TenTheLoai = txtTenTLS_ThemTLS.Text;
                string result = _sqlTheLoai.Insert(_theLoai);
                if (result == "Success")
                {
                    panel_Result.Text = "Đã nhập thể loại sách thành công";
                    UpdateTheLoaiSach();
                }
                else
                {
                    panel_Result.Text = result;
                }
            }
            else
            {
                panel_Result.Text = "Vui lòng nhập tên thể loại";
            }                
        }

        /// <summary>
        /// Nhap du lieu Sach
        /// </summary>
        private void NhapDauSach()
        {
            /************************************************************************/
            /* Phieu Nhap Sach                                                      */
            /************************************************************************/

            _phieuNS.NgayLap = dtimeNgayLap.Text;
            _phieuNS.TongTien = _detail._tongtien;
            _sqlPhieuNS.Insert(_phieuNS);

            //////////////////////////////////////////////////////////////////////////

            foreach (DataRow row in _detail._dataTable.Rows)
            {
                /************************************************************************/
                /* Dau Sach                                                             */
                /************************************************************************/
                string tenDS = (string)row[0];
                _theLoai.TenTheLoai = (string)row["Thể loại"];
                int maTL = (int)(_sqlTheLoai.GetId(_theLoai)).Rows[0][0];

                _dauSach.TenDauSach = tenDS;                
                _sqlDauSach.GetMaDauSach(_dauSach);
                if (_dauSach.MaDauSach == 0)
                {
                    _dauSach.MaTheLoai = maTL;
                    _sqlDauSach.Insert(_dauSach);
                }
                /************************************************************************/
                /* Sach                                                                 */
                /************************************************************************/
                _sach.MaDauSach = 0;
                _sach.MaDauSach = _dauSach.MaDauSach;
                _sach.NhaXuatBan = (string)row["Nhà Xuất Bản"];
                _sach.NamXuatBan = (int)row["Năm Xuất Bản"];
                _sach.SoLuong = (int)row["Số lượng"];
                _sach.GiaTien = (int)row["Giá tiền"];

                _sqlSach.Insert(_sach);
                /************************************************************************/
                /* Cuon Sach                                                            */
                /************************************************************************/
                _cuonSach.MaSach = _sach.MaSach;
                _cuonSach.TinhTrang = 1;
                for (int i = 1; i <= (int)row["Số lượng"]; i++)
                {
                    _sqlCuonSach.Insert(_cuonSach);
                }
                /************************************************************************/
                /* CTPhieu Nhap Sach                                                    */
                /************************************************************************/
                _ctPNS.SoPNS = _phieuNS.SoPNS;
                _ctPNS.MaSach = _sach.MaSach;
                _ctPNS.SoLuongNhap = (int)row["Số lượng"];
                _ctPNS.DonGia = (int)row["Giá tiền"];
                _ctPNS.ThanhTien = (long)row["Tổng tiền"];

                _sqlCTPNS.Insert(_ctPNS);
                /************************************************************************/
                /* CTTac Gia                                                            */
                /************************************************************************/
                _ctTacGia.MaTacGia = (int)cmbTacGia_NhapSach.SelectedValue;
                _ctTacGia.MaDauSach = _dauSach.MaDauSach;

                _sqlCTTacGia.Insert(_ctTacGia);
            }

            MessageBox.Show("Đã nhập thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
            _detail.ResetField();
            ResetField();
        }       
        #endregion

        /// <summary>
        /// Control's event
        /// </summary>        
        #region Controls event
        private void butThoat_Click(object sender, EventArgs e)
        {
            this.IsOpen = false;
        }        

        private void butNhapLai_Click(object sender, EventArgs e)
        {
            ResetField();
        }

        private string checkFillTextInfo()
        {
            if (string.IsNullOrEmpty(cmbTenSach.Text))
                return "Hãy nhập tên sách";
            if (string.IsNullOrEmpty(dtimeNamXB.Text))
                return "Hãy nhập năm xuất bản";
            if (!MainForm._ThamSo.KiemTraNamXuatBan(int.Parse(dtimeNamXB.Text)))
                return MainForm._ThamSo.KiemTraNamXuatBan_Error;
            if (string.IsNullOrEmpty(cmbNhaXB.Text))
                return "Hãy nhập tên nhà xuất bản";            
            if (int.Parse(txtSoLuong.Text) == 0)
                return "Số lượng phải lớn hơn 0";
            if (int.Parse(txtGiaTien.Text) == 0)
                return "Giá tiền phải lớn hơn 0";            
            return "";
        }

        private void butNhapSach_Click(object sender, EventArgs e)
        {
            string result = checkFillTextInfo();
            if (result == "")
            {
                DataRow row = _detail._dataTable.NewRow();

                row[0] = cmbTenSach.Text;
                row[1] = cmbTheLoai.Text;
                row[2] = cmbTacGia_NhapSach.Text;
                row[3] = Int32.Parse(dtimeNamXB.Text);
                row[4] = cmbNhaXB.Text;               
                row[5] = Int32.Parse(txtGiaTien.Text);
                row[6] = Int32.Parse(txtSoLuong.Text);
                row[7] = Int64.Parse(txtTongTien.Text);

                _detail.AddRow(row);
                ResetField();
                panel_Result.Text = "Đã thêm vào chi tiết nhập";
            }
            else
                panel_Result.Text = result;
        }

        private void butNhap_Click(object sender, EventArgs e)
        {
            NhapDauSach();
        }

        private void checkKeyPress_IntValue(object sender, KeyPressEventArgs e)
        {
            if (!char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar) && !char.IsPunctuation(e.KeyChar))
                e.Handled = true;
        }        

        private void butChiTiet_Click(object sender, EventArgs e)
        {
            _detail.ShowSlide();
        }

        private void txtGiaTien_Leave(object sender, EventArgs e)
        {
            txtTongTien.Text = (Int32.Parse(txtGiaTien.Text) * Int32.Parse(txtSoLuong.Text)).ToString();
        }

        private void cmbTenSach_Leave(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(cmbTenSach.Text))
            {
                cmbTenSach.Text = Bussiness_Objects.BusinessRule.ValiadateText.TrimText(cmbTenSach.Text);                
            }
        }

        private void txtField_Leave(object sender, EventArgs e)
        {
            DevComponents.DotNetBar.Controls.TextBoxX text = sender as DevComponents.DotNetBar.Controls.TextBoxX;
            if (!string.IsNullOrEmpty(text.Text))
            {
                text.Text = Bussiness_Objects.BusinessRule.ValiadateText.UpcaseName(text.Text);
            }
        }

        private void dtimeNamXB_TextChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(dtimeNamXB.Text))
            {
                if (MainForm._ThamSo.KiemTraNamXuatBan(int.Parse(dtimeNamXB.Text)))
                {
                    pic_error_NamXB.Visible = false;
                }
                else
                {
                    pic_error_NamXB.Visible = true;
                    panel_Result.Text = MainForm._ThamSo.KiemTraNamXuatBan_Error;
                }
            }
        }
        #endregion                             

        private void dtimeNgayLap_ValueChanged(object sender, EventArgs e)
        {
            _detail.dateTime.Value = dtimeNgayLap.Value;
        }

        void dateTime_ValueChanged(object sender, EventArgs e)
        {
            dtimeNgayLap.Value = _detail.dateTime.Value;
        }
    }
}